package com.hm.controller;

import com.hm.pojo.Result;
import com.hm.pojo.User;
import com.hm.service.UserService;
import com.hm.utils.JwtUtil;
import com.hm.utils.Md5Util;
import com.hm.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    /***
     * 注册
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$", message = "用户名格式错误") String username,
                           @Pattern(regexp = "^\\S{5,16}$", message = "密码格式错误") String password) {
        // 先判断是有重复的用户名
        User user = userService.findUserByUsername(username);
        if (user == null){//  没有重复
            userService.insertUser(username, password);
            return Result.success("注册成功");
        } else { //  有重复
            return Result.error("用户名重复");
        }
    }

    /***
     * 登录
     * @return
     */
    @PostMapping(value = "/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$", message = "用户名格式错误") String username,
                           @Pattern(regexp = "^\\S{5,16}$", message = "密码格式错误") String password) {
        User user = userService.findUserByUsername(username);
        if (user == null){ //  没有该用户
            return Result.error("该用户不存在");
        } else { //  有该用户
            if (Md5Util.checkPassword(password, user.getPassword())){ //  密码正确
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("username", user.getUsername());
                map.put("id", user.getId());
                String token = JwtUtil.genToken(map);
                return Result.success(token);
            } else { //  密码错误
                return Result.error("密码错误");
            }
        }
    }

    /***
     * 获取用户信息
     * @return
     */
    @GetMapping(value =  "/userInfo")
    public Result  getUserInfo(/** @RequestHeader("Authorization") String authorization **/) {
//        Map<String, Object> map = JwtUtil.parseToken(authorization);
        // 改为从ThreadLocal中获取
        Map<String, Object> map = ThreadLocalUtil.get();
        User user = userService.findUserByUsername((String) map.get("username"));
        return Result.success(user);
    }

    /**
     * 更新用户信息
     *
     * 该方法通过HTTP PUT请求接收一个用户对象，用于更新用户信息
     * 使用@PutMapping注解指定请求路径和方法，@RequestBody注解用于将HTTP请求正文转换为User对象，
     * @Validated注解用于验证传入的User对象属性是否符合规范
     *
     * @param user 待更新的用户对象，需要通过JSON格式传入请求体中
     * @return 返回一个Result对象，表示更新操作的结果
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatar){
        userService.updateAvata(avatar);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody  Map<String,String> params){
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        log.info("oldPwd: " + oldPwd + " newPwd: " + newPwd + " rePwd: " + rePwd);
        // 先判空
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("请输入完整信息");
        }
        // 验证旧密码
        Map<String,Object>  map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findUserByUsername(username);
        if (!Md5Util.checkPassword(oldPwd, user.getPassword())){
            return Result.error("旧密码错误");
        }
        // 验证新密码
        if (!newPwd.equals(rePwd)){
            return Result.error("新密码不一致");
        }
        // 更新
        userService.updatePwd(Md5Util.getMD5String(newPwd));
        return Result.success();
    }



}
